package com.cnaaa.pay.conf;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.cnaaa.pay.bo.AlipayKey;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 2018/10/26 Create by 郭文梁
 * AlipayConfiguration
 * 配置支付宝客户端
 *
 * @author 郭文梁
 * @date 2018/10/26
 */
@Configuration
public class AlipayConfiguration {
    private static final Charset DEFAULT_CHARSET = Charset.defaultCharset();
    private final AlipayConfigurationProperties configurationProperties;

    @Autowired
    public AlipayConfiguration(AlipayConfigurationProperties configurationProperties) {
        this.configurationProperties = configurationProperties;
    }

    @Bean
    public AlipayClient alipayClient() {
        String appId = configurationProperties.getAppId();
        String alipayGateway = configurationProperties.getAlipayGateway();
        AlipayKey alipayKey = readKeyFile();
        String privateKey = alipayKey.getPrivateKey();
        String publicKey = alipayKey.getPublicKey();
        String format = configurationProperties.getFormat();
        String charset = configurationProperties.getCharset();
        String signType = configurationProperties.getSignType();
        return new DefaultAlipayClient(
                alipayGateway,
                appId,
                privateKey,
                format,
                charset,
                publicKey,
                signType);
    }

    private String readFileAsString(String privateKeyFileName) {
        try {
            return IOUtils.resourceToString(privateKeyFileName, DEFAULT_CHARSET);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private AlipayKey readKeyFile() {
        String privateKey = readFileAsString(configurationProperties.getPrivateKeyFileName());
        String publicKey = readFileAsString(configurationProperties.getPublicKeyFileName());
        configurationProperties.setPublicKey(publicKey);
        configurationProperties.setPrivateKey(privateKey);
        return new AlipayKey(privateKey, publicKey);
    }
}
